package route

import (
	"fmt"
	"log"
	"net/http"
)

type Mux struct {
	mux      http.ServeMux
	pool     map[string]string                                  // 路由池
	groups   map[string]string                                  // 路由组
	authFunc func(w *http.ResponseWriter, r *http.Request) bool // 鉴权组件
	cors     bool                                               // 允许跨域
	map_s    string                                             // 路由map缓存
}

// 服务运行
func (m *Mux) Serve(addr string) {
	log.Printf("HTTP服务运行在%s", addr)
	err := http.ListenAndServe(addr, &m.mux)
	if err != nil {
		log.Panic(err.Error())
	}
}

func (m *Mux) ServerTLS(addr string, cert string, key string) {
	log.Printf("HTTPS服务运行在%s", addr)
	err := http.ListenAndServeTLS(addr, cert, key, &m.mux)
	if err != nil {
		log.Panic(err.Error())
	}
}

// 打印路由列表
func (m *Mux) ShowRouteMap() string {
	if m.map_s != "" {
		return m.map_s
	}
	s := "\n路由组(仅分组说明，无实际功能)\n------"
	for k, v := range m.groups {
		s = fmt.Sprintf("%s\n%s\t\t%s", s, k, v)
	}
	s += "\n\n路由明细\n------"
	for k, v := range m.pool {
		s = fmt.Sprintf("%s\n%s\t\t%s", s, k, v)
	}
	log.Println(s)
	m.map_s = s
	return s
}
